package cn.smvc.task.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.springframework.stereotype.Repository;

import cn.smvc.common.dao.JDBCUtils;
import cn.smvc.common.utils.StringUtils;
import cn.smvc.task.dao.TTimedTaskLogDao;
import cn.smvc.task.entity.TTimedTaskLog;

@Repository
public class TTimedTaskLogDaoImpl implements TTimedTaskLogDao{
	/*
	 * 这两个是处理数据库表字段下划线的，
	 * 		与实体类中的属性对应（驼峰规则）
	 */
	BeanProcessor bean = new GenerousBeanProcessor();
	RowProcessor processor = new BasicRowProcessor(bean);

	@Override
	public int save(TTimedTaskLog taskLog) throws SQLException {
		// sql
		String sql = "insert into t_timed_task_log values(null,?,?,?,?,?,?,?,?) ";
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存信息
			result = queryRunner.update(JDBCUtils.getConnection(), 
					sql, 
					taskLog.getTaskId(),
					taskLog.getTaskName(),
					taskLog.getTaskGroup(),
					taskLog.getStartTime(),
					taskLog.getEndTime(),
					taskLog.getExeTimeLong(),
					taskLog.getExeResult(),
					taskLog.getCreateTime());
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}

	@Override
	public List<TTimedTaskLog> findPage(String where, int page, int limit, String orderBy) throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t_timed_task_log where ").append(where);
		if(StringUtils.isNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy);
		}
		sb.append(" limit ").append((page - 1) * limit).append(", ").append(limit);
		List<TTimedTaskLog> list = null;
		list = queryRunner.query(sb.toString(), new BeanListHandler<TTimedTaskLog>(TTimedTaskLog.class, processor));
		return list;
	}

	@Override
	public int count(String where) throws SQLException {
//		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
//		StringBuilder sql = new StringBuilder();
//		sql
//		.append("select count(*) from t_timed_task_log where ")
//		.append(where);
//		Long count = queryRunner.query(sql.toString(), new ScalarHandler<Long>());
		
		return 0;
	}

}
